<template>
  <div class="order-edit-container">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <el-button @click="handleGoBack">
        <el-icon><ArrowLeft /></el-icon> 返回列表
      </el-button>
      <h1>编辑订单</h1>
      <div class="action-buttons">
        <el-button @click="resetForm">
          <el-icon><Refresh /></el-icon> 重置
        </el-button>
        <el-button type="primary" @click="submitForm">
          <el-icon><Check /></el-icon> 保存
        </el-button>
      </div>
    </div>

    <!-- 表单卡片 -->
    <el-card class="main-card">
      <el-form
        ref="orderFormRef"
        :model="orderForm"
        :rules="orderRules"
        label-width="120px"
        size="default"
        class="order-form"
      >
        <!-- 基本信息区域 -->
        <div class="form-section">
          <h2 class="section-title">基本信息</h2>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="订单编号">
                <el-input v-model="orderForm.orderNo" disabled placeholder="系统自动生成"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="订单状态">
                <el-tag :type="getStatusTagType(orderForm.status)">{{ getStatusText(orderForm.status) }}</el-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="订单类型" prop="type">
                <el-select v-model="orderForm.type" placeholder="请选择订单类型" :disabled="!canEditBasicInfo">
                  <el-option v-for="item in orderTypeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="订单日期" prop="orderDate">
                <el-date-picker
                  v-model="orderForm.orderDate"
                  type="date"
                  placeholder="选择日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  :disabled="!canEditBasicInfo"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="供应商" prop="supplierId">
                <el-select v-model="orderForm.supplierId" placeholder="请选择供应商" filterable @change="handleSupplierChange" :disabled="!canEditBasicInfo">
                  <el-option v-for="item in supplierOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系人">
                <el-input v-model="supplierContact" disabled placeholder="供应商联系人"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话">
                <el-input v-model="supplierPhone" disabled placeholder="供应商电话"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="收货地址" prop="address">
                <el-input v-model="orderForm.address" placeholder="请输入收货地址"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="收货单位" prop="receiveUnit">
                <el-input v-model="orderForm.receiveUnit" placeholder="请输入收货单位"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="预计交付日期" prop="expectedDeliveryDate">
                <el-date-picker
                  v-model="orderForm.expectedDeliveryDate"
                  type="date"
                  placeholder="选择日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注信息" prop="remark">
                <el-input v-model="orderForm.remark" type="textarea" rows="3" placeholder="请输入备注信息"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 商品列表区域 -->
        <div class="form-section">
          <div class="section-header">
            <h2 class="section-title">商品清单</h2>
            <el-button type="primary" size="small" @click="addProduct" :disabled="!canEditProducts">
              <el-icon><Plus /></el-icon> 添加商品
            </el-button>
          </div>

          <el-table
            :data="orderForm.products"
            border
            stripe
            size="small"
            class="product-table"
          >
            <el-table-column type="index" label="序号" width="60"></el-table-column>
            <el-table-column prop="productName" label="商品名称" min-width="200">
              <template #default="scope">
                <el-form-item
                  :prop="`products.${scope.$index}.productId`"
                  :rules="productRules.productId"
                  class="product-form-item"
                >
                  <el-select
                    v-model="scope.row.productId"
                    placeholder="请选择商品"
                    filterable
                    @change="handleProductChange(scope.row, scope.$index)"
                    :disabled="!canEditProducts"
                  >
                    <el-option v-for="item in productOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="productCode" label="商品编码" min-width="120">
              <template #default="scope">
                <el-input v-model="scope.row.productCode" disabled placeholder="商品编码"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="specification" label="规格型号" min-width="150">
              <template #default="scope">
                <el-input v-model="scope.row.specification" disabled placeholder="规格型号"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="unit" label="单位" min-width="80">
              <template #default="scope">
                <el-input v-model="scope.row.unit" disabled placeholder="单位"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="单价" min-width="100" align="right">
              <template #default="scope">
                <el-form-item
                  :prop="`products.${scope.$index}.price`"
                  :rules="productRules.price"
                  class="product-form-item"
                >
                  <el-input
                    v-model.number="scope.row.price"
                    type="number"
                    placeholder="0.00"
                    @change="calculateProductAmount(scope.$index)"
                    :disabled="!canEditProducts"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" min-width="100" align="right">
              <template #default="scope">
                <el-form-item
                  :prop="`products.${scope.$index}.quantity`"
                  :rules="productRules.quantity"
                  class="product-form-item"
                >
                  <el-input
                    v-model.number="scope.row.quantity"
                    type="number"
                    min="1"
                    placeholder="1"
                    @change="calculateProductAmount(scope.$index)"
                    :disabled="!canEditProducts"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="discount" label="折扣(%)" min-width="100" align="right">
              <template #default="scope">
                <el-form-item
                  :prop="`products.${scope.$index}.discount`"
                  :rules="productRules.discount"
                  class="product-form-item"
                >
                  <el-input
                    v-model.number="scope.row.discount"
                    type="number"
                    min="0"
                    max="100"
                    placeholder="100"
                    @change="calculateProductAmount(scope.$index)"
                    :disabled="!canEditProducts"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="金额" min-width="100" align="right">
              <template #default="scope">
                <el-input v-model="scope.row.amount" disabled placeholder="0.00" :formatter="formatCurrency"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="80" align="center">
              <template #default="scope">
                <el-button
                  type="text"
                  size="small"
                  text-color="#ff4d4f"
                  @click="removeProduct(scope.$index)"
                  :disabled="!canEditProducts || orderForm.products.length <= 1"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 金额汇总 -->
          <div class="amount-summary">
            <div class="summary-item">
              <span class="label">商品总金额：</span>
              <span class="value">{{ formatCurrency(subtotalAmount) }}</span>
            </div>
            <div class="summary-item">
              <span class="label">折扣金额：</span>
              <span class="value">{{ formatCurrency(discountAmount) }}</span>
            </div>
            <div class="summary-item">
              <span class="label">运费：</span>
              <el-form-item prop="freight" class="freight-form-item">
                <el-input
                  v-model.number="orderForm.freight"
                  type="number"
                  placeholder="0.00"
                  @change="calculateTotalAmount"
                ></el-input>
              </el-form-item>
            </div>
            <div class="summary-item total-amount">
              <span class="label">订单总金额：</span>
              <span class="value">{{ formatCurrency(orderForm.totalAmount) }}</span>
            </div>
          </div>
        </div>

        <!-- 支付信息区域 -->
        <div class="form-section">
          <h2 class="section-title">支付信息</h2>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="支付方式" prop="paymentMethod">
                <el-select v-model="orderForm.paymentMethod" placeholder="请选择支付方式">
                  <el-option v-for="item in paymentMethodOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="银行账户" prop="bankAccount">
                <el-input v-model="orderForm.bankAccount" placeholder="请输入银行账户"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发票类型" prop="invoiceType">
                <el-select v-model="orderForm.invoiceType" placeholder="请选择发票类型">
                  <el-option v-for="item in invoiceTypeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="税率(%)" prop="taxRate">
                <el-input v-model.number="orderForm.taxRate" type="number" min="0" max="100" placeholder="13"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import {
  ArrowLeft,
  Check,
  Refresh,
  Plus
} from '@element-plus/icons-vue';
import { ElMessage, ElLoading, ElForm } from 'element-plus';

// 路由实例
const router = useRouter();
const route = useRoute();

// 表单引用
const orderFormRef = ref<InstanceType<typeof ElForm>>();
const loading = ref(true);

// 订单ID
const orderId = route.params.id as string;

// 订单表单数据
const orderForm = reactive({
  id: '',
  orderNo: '',
  status: 0,
  type: '',
  orderDate: new Date().toISOString().slice(0, 10),
  supplierId: '',
  address: '',
  receiveUnit: '',
  expectedDeliveryDate: '',
  remark: '',
  freight: 0,
  totalAmount: 0,
  paymentMethod: '',
  bankAccount: '',
  invoiceType: '',
  taxRate: 13,
  products: [{
    productId: '',
    productName: '',
    productCode: '',
    specification: '',
    unit: '',
    price: 0,
    quantity: 1,
    discount: 100,
    amount: 0
  }]
});

// 供应商联系人信息
const supplierContact = ref('');
const supplierPhone = ref('');

// 判断是否可以编辑基本信息（根据订单状态）
const canEditBasicInfo = computed(() => {
  // 只有待确认和已确认状态可以编辑基本信息
  return [0, 1].includes(orderForm.status);
});

// 判断是否可以编辑商品信息（根据订单状态）
const canEditProducts = computed(() => {
  // 只有待确认和已确认状态可以编辑商品信息
  return [0, 1].includes(orderForm.status);
});

// 订单类型选项
const orderTypeOptions = [
  { value: '1', label: '采购订单' },
  { value: '2', label: '销售订单' },
  { value: '3', label: '退货订单' }
];

// 支付方式选项
const paymentMethodOptions = [
  { value: '1', label: '银行转账' },
  { value: '2', label: '支付宝' },
  { value: '3', label: '微信支付' },
  { value: '4', label: '支票' }
];

// 发票类型选项
const invoiceTypeOptions = [
  { value: '1', label: '增值税专用发票' },
  { value: '2', label: '增值税普通发票' },
  { value: '3', label: '电子发票' },
  { value: '4', label: '无发票' }
];

// 模拟供应商数据
const supplierOptions = ref([
  { id: '1', name: '阿里巴巴科技有限公司', contact: '张三', phone: '13800138000' },
  { id: '2', name: '腾讯云计算有限公司', contact: '李四', phone: '13900139000' },
  { id: '3', name: '华为技术有限公司', contact: '王五', phone: '13700137000' },
  { id: '4', name: '百度在线网络技术有限公司', contact: '赵六', phone: '13600136000' },
  { id: '5', name: '京东科技控股股份有限公司', contact: '钱七', phone: '13500135000' }
]);

// 模拟商品数据
const productOptions = ref([
  { id: '1', name: '高性能笔记本电脑', code: 'NB-2023-001', specification: 'i7/16G/1TB/14英寸', unit: '台', price: 8999 },
  { id: '2', name: '无线鼠标', code: 'MS-2023-002', specification: '蓝牙/黑色', unit: '个', price: 129 },
  { id: '3', name: '机械键盘', code: 'KB-2023-003', specification: '青轴/背光/有线', unit: '个', price: 399 },
  { id: '4', name: '27英寸显示器', code: 'MN-2023-004', specification: '4K/IPS/60Hz', unit: '台', price: 2499 },
  { id: '5', name: '投影仪', code: 'PJ-2023-005', specification: '1080P/4000流明', unit: '台', price: 3699 },
  { id: '6', name: '打印机', code: 'PR-2023-006', specification: '彩色/无线/喷墨', unit: '台', price: 1299 },
  { id: '7', name: '办公椅', code: 'CH-2023-007', specification: '人体工学/可调节', unit: '把', price: 899 },
  { id: '8', name: '办公桌', code: 'TB-2023-008', specification: '1.4m/实木', unit: '张', price: 1599 }
]);

// 订单表单验证规则
const orderRules = reactive({
  type: [{ required: true, message: '请选择订单类型', trigger: 'change' }],
  orderDate: [{ required: true, message: '请选择订单日期', trigger: 'change' }],
  supplierId: [{ required: true, message: '请选择供应商', trigger: 'change' }],
  address: [{ required: true, message: '请输入收货地址', trigger: 'blur' }],
  receiveUnit: [{ required: true, message: '请输入收货单位', trigger: 'blur' }],
  expectedDeliveryDate: [{ required: true, message: '请选择预计交付日期', trigger: 'change' }],
  freight: [{ required: true, message: '请输入运费', trigger: 'blur' }],
  paymentMethod: [{ required: true, message: '请选择支付方式', trigger: 'change' }],
  invoiceType: [{ required: true, message: '请选择发票类型', trigger: 'change' }],
  taxRate: [{ required: true, message: '请输入税率', trigger: 'blur' }]
});

// 商品表单验证规则
const productRules = reactive({
  productId: [{ required: true, message: '请选择商品', trigger: 'change' }],
  price: [
    { required: true, message: '请输入单价', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '单价必须大于0', trigger: 'blur' }
  ],
  quantity: [
    { required: true, message: '请输入数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
  ],
  discount: [
    { required: true, message: '请输入折扣', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '折扣必须在0-100之间', trigger: 'blur' }
  ]
});

// 计算商品总金额
const subtotalAmount = computed(() => {
  return orderForm.products.reduce((sum, item) => sum + (item.amount || 0), 0);
});

// 计算折扣金额
const discountAmount = computed(() => {
  const originalTotal = orderForm.products.reduce((sum, item) => sum + (item.price * item.quantity || 0), 0);
  return originalTotal - subtotalAmount.value;
});

// 格式化金额显示
const formatCurrency = (value: number) => {
  if (!value) return '¥0.00';
  return '¥' + value.toFixed(2);
};

// 获取订单状态文本
const getStatusText = (status: number): string => {
  const statusMap = {
    0: '待确认',
    1: '已确认',
    2: '已发货',
    3: '已收货',
    4: '已完成',
    5: '已取消',
    6: '异常'
  };
  return statusMap[status] || '未知';
};

// 获取订单状态标签类型
const getStatusTagType = (status: number): string => {
  const typeMap = {
    0: 'info',
    1: 'primary',
    2: 'success',
    3: 'processing',
    4: 'success',
    5: 'danger',
    6: 'warning'
  };
  return typeMap[status] || 'default';
};

// 选择供应商变化
const handleSupplierChange = (supplierId: string) => {
  const supplier = supplierOptions.value.find(item => item.id === supplierId);
  if (supplier) {
    supplierContact.value = supplier.contact;
    supplierPhone.value = supplier.phone;
  } else {
    supplierContact.value = '';
    supplierPhone.value = '';
  }
};

// 选择商品变化
const handleProductChange = (product: any, index: number) => {
  const selectedProduct = productOptions.value.find(item => item.id === product.productId);
  if (selectedProduct) {
    product.productName = selectedProduct.name;
    product.productCode = selectedProduct.code;
    product.specification = selectedProduct.specification;
    product.unit = selectedProduct.unit;
    product.price = selectedProduct.price;
    calculateProductAmount(index);
  }
};

// 计算商品金额
const calculateProductAmount = (index: number) => {
  const product = orderForm.products[index];
  if (product.price && product.quantity && product.discount) {
    product.amount = (product.price * product.quantity * product.discount) / 100;
    calculateTotalAmount();
  }
};

// 计算订单总金额
const calculateTotalAmount = () => {
  orderForm.totalAmount = subtotalAmount.value + Number(orderForm.freight || 0);
};

// 添加商品
const addProduct = () => {
  orderForm.products.push({
    productId: '',
    productName: '',
    productCode: '',
    specification: '',
    unit: '',
    price: 0,
    quantity: 1,
    discount: 100,
    amount: 0
  });

  // 延迟执行，确保DOM已更新
  nextTick(() => {
    // 滚动到表格底部
    const table = document.querySelector('.product-table');
    if (table) {
      table.scrollTop = table.scrollHeight;
    }
  });
};

// 删除商品
const removeProduct = (index: number) => {
  orderForm.products.splice(index, 1);
  calculateTotalAmount();
};

// 提交表单
const submitForm = async () => {
  if (!orderFormRef.value) return;

  try {
    // 表单验证
    await orderFormRef.value.validate();

    // 显示加载中
    const loading = ElLoading.service({
      lock: true,
      text: '保存中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    // 模拟API请求
    setTimeout(() => {
      loading.close();
      ElMessage.success('订单更新成功');
      router.push({ name: 'OrderList' });
    }, 1500);
  } catch (error) {
    ElMessage.error('表单验证失败，请检查填写内容');
    console.error('表单验证失败:', error);
  }
};

// 重置表单
const resetForm = () => {
  if (orderFormRef.value) {
    orderFormRef.value.resetFields();
  }
};

// 返回列表
const handleGoBack = () => {
  router.push({ name: 'OrderList' });
};

// 获取订单详情
const fetchOrderDetail = async () => {
  loading.value = true;
  try {
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 1000));

    // 生成模拟数据
    const now = new Date();
    const randomStatus = Math.floor(Math.random() * 4); // 0-3之间的随机状态
    const randomTypeIndex = Math.floor(Math.random() * 3);
    const randomSupplierIndex = Math.floor(Math.random() * supplierOptions.value.length);
    const supplier = supplierOptions.value[randomSupplierIndex];

    // 生成随机商品数据
    const products = [];
    const productCount = Math.floor(Math.random() * 3) + 2; // 2-4个商品
    for (let i = 0; i < productCount; i++) {
      const randomProductIndex = Math.floor(Math.random() * productOptions.value.length);
      const product = productOptions.value[randomProductIndex];
      const quantity = Math.floor(Math.random() * 10) + 1;
      const discount = 100 - Math.floor(Math.random() * 10); // 90-100折
      const price = product.price;
      const amount = (price * quantity * discount) / 100;

      products.push({
        productId: product.id,
        productName: product.name,
        productCode: product.code,
        specification: product.specification,
        unit: product.unit,
        price: price,
        quantity: quantity,
        discount: discount,
        amount: amount
      });
    }

    // 计算总金额
    const subtotal = products.reduce((sum, item) => sum + item.amount, 0);
    const freight = subtotal > 1000 ? 0 : 50;
    const totalAmount = subtotal + freight;

    // 设置订单详情数据
    Object.assign(orderForm, {
      id: orderId,
      orderNo: `ZCY${Date.now().toString().slice(-10)}`,
      status: randomStatus,
      type: (randomTypeIndex + 1).toString(),
      orderDate: new Date(now.getTime() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000).toISOString().slice(0, 10),
      supplierId: supplier.id,
      address: `${['浙江省', '北京市', '上海市'][Math.floor(Math.random() * 3)]}${['杭州市', '北京市', '上海市'][Math.floor(Math.random() * 3)]}测试地址${Math.floor(Math.random() * 100)}号`,
      receiveUnit: `收货单位${Math.floor(Math.random() * 100)}`,
      expectedDeliveryDate: new Date(now.getTime() + Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000).toISOString().slice(0, 10),
      remark: Math.random() > 0.3 ? '这是一个订单备注信息，包含订单的特殊要求和说明...' : '',
      freight: freight,
      totalAmount: totalAmount,
      paymentMethod: (Math.floor(Math.random() * 4) + 1).toString(),
      bankAccount: Math.random() > 0.5 ? `6222 **** **** ${Math.floor(Math.random() * 10000).toString().padStart(4, '0')}` : '',
      invoiceType: (Math.floor(Math.random() * 4) + 1).toString(),
      taxRate: 13,
      products: products
    });

    // 设置供应商联系人信息
    supplierContact.value = supplier.contact;
    supplierPhone.value = supplier.phone;
  } catch (error) {
    ElMessage.error('获取订单详情失败');
    console.error('获取订单详情失败:', error);
  } finally {
    loading.value = false;
  }
};

// 页面加载时初始化
onMounted(() => {
  fetchOrderDetail();
});
</script>

<style scoped lang="scss">
.order-edit-container {
  padding: 0 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.main-card {
  margin-bottom: 20px;
}

.form-section {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px dashed #eee;
}

.form-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  padding-left: 5px;
  border-left: 3px solid #409eff;
  margin-bottom: 15px;
}

.product-table {
  margin-bottom: 20px;
}

.product-form-item {
  margin-bottom: 0;
}

.amount-summary {
  margin-top: 15px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-end;
  gap: 20px 40px;
  align-items: center;
}

.summary-item {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.label {
  color: #606266;
  margin-right: 10px;
  white-space: nowrap;
}

.value {
  font-weight: 500;
}

.total-amount {
  font-size: 16px;
  color: #f56c6c;
}

.freight-form-item {
  margin-bottom: 0;
  width: 120px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .order-edit-container {
    padding: 0 10px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .action-buttons {
    width: 100%;
    justify-content: flex-end;
  }

  .amount-summary {
    flex-direction: column;
    align-items: flex-end;
  }
}
</style>